package cn.kgc.userprovider.service.impl;

import cn.kgc.qg.common.ResponseCode;
import cn.kgc.qg.common.ServerResponse;
import cn.kgc.qg.dao.user.QgUserMapper;
import cn.kgc.qg.pojo.user.QgUser;
import cn.kgc.qg.service.user.TokenService;
import cn.kgc.qg.service.user.UserService;

import cn.kgc.qg.utils.MD5Util;
import cn.kgc.qg.utils.RedisUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Service(interfaceClass = UserService.class)
public class  UserServiceImpl implements UserService {

    @Resource
    private QgUserMapper qgUserMapper;

    @Override
    public QgUser queryUserById(Integer integer) {
        System.out.println(">>>>>>>>>>>> 用户模块服务提供者 测试调用....... ");
        return qgUserMapper.selectByPrimaryKey(integer.toString());
    }

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private TokenService tokenService;

    @Override
    public QgUser queryUserByld(Integer integer) {
        return null;
    }

    @Override
    public ServerResponse userLogin(String phone, String password, String userAgent) {

        // 校验参数
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(password) || StringUtils.isBlank(userAgent)) {
            return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        // 查询用户
        QgUser qgUser = qgUserMapper.queryUserByPhone(phone);
        if (qgUser == null) {
            // 用户名不存在
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        // TODO 加密密码
        String md5EncodeUtf8 = MD5Util.MD5EncodeUtf8(password);
        if (! StringUtils.equals(md5EncodeUtf8,qgUser.getPassword())){
            return ServerResponse.createByErrorMessage("密码不正确");
        }
        // TODO 生成TOKEN
        String token = tokenService.generateToken(userAgent, qgUser);

        // 判断redis中是否有token存在
        String oldToken = redisUtil.getStr(qgUser.getId());
        if (oldToken != null){
            // 如果redis中存在数据，则删除指定token
            redisUtil.del(oldToken);
        }
        tokenService.saveToken(token, qgUser, userAgent);
        redisUtil.setStr(qgUser.getId(),token,120L);
        System.out.println("<<<<<<<<< token 保存完成");
        return ServerResponse.createBySuccess(token);
    }

}
